const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../../utils/validate.js'
import {
  reqSpaceEdit,
  reqSpaceImage,
  reqDeviceBySpaceId,
  reqDeviceByImei,
  reqDeviceAdd,
  reqDeviceUnBind,
  reqAlarmReceiverList,
  reqReceiverSpaceAdd,
  reqAlarmReceiverBySpaceId
} from '../../../../../request/api'
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    spaceInfo: {
      type: Object,
      value: {},
    }
  },


  data: {
    form: {
      id: '',
      name: '',
      address: '',
      isDefence: false,
      buildingType: 3, //空间类型 
      orgId: ""
    },
    imageList: [],
    imageCount: 6, //照片数量限制6张
    disabledBtn: false,
  },

  attached() {},

  observers: {
    'spaceInfo': function (newVal) {
      this.setData({
        'form.id': newVal.id,
        'form.name': newVal.name,
        'form.address': newVal.address,
        'form.isDefence': newVal.isDefence === 1 ? true : false,
        'form.orgId': newVal.orgId,
      })
      if (newVal.id) {
        this.getSpaceImage()
      }
    }
  },


  methods: {

    // 获取照片信息
    async getSpaceImage() {
      let list = this.data.imageList
      if (list.length > 0) return
      const res = await reqSpaceImage(this.data.form.id)
      if (res.code != 20000) return showMsg(res.message);
      let {
        rows
      } = res.data
      if (rows && rows.length <= 0) return
      let imageList = []
      rows.forEach((item, index) => {
        imageList.push({
          id: index,
          src: item
        })
      })
      this.setData({
        imageList,
        imageCount: 6 - imageList.length
      })
    },
    // 点击布撤防
    changeDefence(e) {
      let tip = e.detail ? '此操作将开启该安装点所有设备布防设置，是否继续？' : '此操作将关闭该安装点所有设备布防设置，是否继续？'
      Dialog.confirm({
          title: '温馨提示',
          message: tip,
        })
        .then(async () => {
          this.setData({
            "form.isDefence": e.detail
          })
        })
        .catch(() => {});
    },
    // 单个添加获取名称
    nameChange(e) {
      // 正则表达式
      //  let value = e.detail.value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
      //  value = value.replace(/\-{2,}/g, "-"); // -只能保留一个
      //  value = value.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
      //  value = value.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
      //  value = value.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
      //  if(value>50){
      //     value=50
      //  }
      //  if(value<-3){
      //     value=-3
      //  }
      //  if(value=='0'){
      //     value=1
      //  }
      this.data.form.name = validateEmoji(e.detail.value.replace(/\s+/g, ''))
      this.setData({
        "form.name": this.data.form.name
      })
    },
    // 单个添加清除
    clearname() {
      this.setData({
        'form.name': ''
      })
    },

    // ------------照片开始
    addImage() {
      let {
        imageList
      } = this.data
      if (imageList.length >= 6) return showMsg("安装照片最多添加6张")
      this.uploadFileFun()
    },
    uploadFileFun(updateItem) {
      let that = this
      wx.chooseImage({
        count: this.data.imageCount,
        success(res) {
          // console.log(res);

          var PicNums = res.tempFiles.length;
          for (var inta = 0; inta < PicNums; inta++) {
            var path = res.tempFiles[inta].path;
            var formatImage = path.split(".")[(path.split(".")).length - 1];
            console.log("图片格式" + formatImage)
            // 判断格式
            if (formatImage != "png" && formatImage != "jpg") {
              showMsg("只能上传.png、.jpg格式")
            }
            // 判断大小
            let size = res.tempFiles.every(item => { //限制上传图片大小为2M,所有图片少于2M才能上传  
              return item.size <= 20000000 //return item.size <= 2000000  500000
            })
            console.log(size);
            if (!size) {
              showMsg("图片大小不能超过20MB!")
              return;
            }
          }


          const tempFilePaths = res.tempFilePaths
          if (tempFilePaths.length > 6) return showMsg("安装照片最多添加6张")

          tempFilePaths.forEach(item => {
            wx.uploadFile({
              url: app.globalData.reqUrl + 'file/upload',
              filePath: item,
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data"
              },
              formData: {
                "token": app.globalData.token,
                "file": item,
              },
              success: function (res) {
                let data = JSON.parse(res.data)
                // console.log(data);
                if (data.code == 20000) {
                  that.updateImageList(data.data.url, updateItem)
                  return showMsg("上传成功")
                } else {
                  return showMsg("上传失败")
                }
              },
              fail: function (e) {
                return showMsg("上传失败")
              }
            })
          })

        }
      })
    },
    // 上传成功后更新照片列表
    updateImageList(url, updateItem) {
      let {
        imageList
      } = this.data
      if (updateItem && updateItem.src) {
        // 更新图片
        imageList.forEach(citem => {
          if (citem.id === updateItem.id) {
            citem.src = url
          }
        })
        imageList.forEach((citem, index) => {
          citem.id = index
        })
        this.setData({
          imageList,
          imageCount: 6 - imageList.length
        })

      } else {
        // 添加图片 
        // console.log(imageList.length);
        let id = 0
        if (imageList.length > 0) {
          id = imageList.length
        }
        imageList.push({
          id,
          src: url
        })
        this.setData({
          imageList,
          imageCount: 6 - imageList.length
        })
      }

      // console.log(this.data.imageList);
    },

    // 点击照片  发生的操作：预览、编辑、删除
    iamgeClick(e) {
      let {
        item
      } = e.currentTarget.dataset
      let that = this
      wx.showActionSheet({
        itemList: ['预览图片', '更新图片'],
        success(res) {
          let {
            tapIndex
          } = res
          if (tapIndex === 0) {
            that.previewImageFun(item)
          } else if (tapIndex === 1) {
            that.updateImageFun(item)
          } else {
            that.delImageFUn(item)
          }
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    },
    // 1、预览图片
    previewImageFun(item) {
      let {
        imageList
      } = this.data
      let urls = imageList.map(item => {
        return item.src
      })
      wx.previewImage({
        current: item.src, // 当前显示图片的http链接
        urls, // 需要预览的图片http链接列表
      })
    },
    // 2、更新图片
    updateImageFun(item) {
      this.uploadFileFun(item)
    },
    // 3、删除图片
    delImageFUn(e) {
      let {
        item
      } = e.currentTarget.dataset
      let {
        imageList
      } = this.data
      imageList.forEach(citem => {
        if (citem.id === item.id) {
          imageList.splice(item.id, 1)
        }
      })
      imageList.forEach((citem, index) => {
        citem.id = index
      })
      this.setData({
        imageList,
        imageCount: 6 - imageList.length
      })
    },
    // ------------照片结束

    // 确认编辑楼层
    async confirm() {
      if (this.data.disabledBtn) return
      let {
        form,
        imageList
      } = this.data
      if (imageList.length > 6) return showMsg("安装照片最多添加6张")
      let picList = imageList.map(item => {
        return item.src
      })
      if (!(form.name)) return showMsg("请输入名称")
      if (!validateSpecial(form.name)) return
      let params = {
        parkId: this.data.parkId,
        id: form.id,
        name: form.name,
        lng: '',
        lat: '',
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        area: '',
        areaCode: '',
        street: '',
        streetCode: '',
        address: '',
        isDefence: form.isDefence ? 1 : 0,
        buildingType: form.buildingType,
        picList,
        village: ''
      }
      // await this.reqReceiverSpace() // 安装点设备修改
      // await this.receiverSpaceAddFun() //接警人新增
      await this.reqSpaceAddFun(params)
    },
    async reqSpaceAddFun(params) {
      const res = await reqSpaceEdit(params)
      if (res.code != 20000) return showMsg(res.message);
      showMsg("编辑成功", "success")
      this.setData({
        disabledBtn: true
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 2000)
    },

  }
})